package edu.gzhu.guli.core.modelmapper;

import org.modelmapper.ModelMapper;
import org.modelmapper.PropertyMap;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Configuration
public class ModelMapperConfig {

  @Bean
  ModelMapper modelMapper() {
    return new ModelMapper();
  }

  @Component
  static class ModelMapperBeanProcessor implements BeanPostProcessor {

    private final ModelMapper modelMapper;

    public ModelMapperBeanProcessor(ModelMapper modelMapper) {
      this.modelMapper = modelMapper;
      modelMapper.getConfiguration().setAmbiguityIgnored(true);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
      if (!(bean instanceof PropertyMap)) {
        return bean;
      }
      modelMapper.addMappings((PropertyMap<?, ?>) bean);
      return bean;
    }
  }
}
